<?php

/**
 * 
 */
class Model_Mapper_Auth extends App_Model_Mapper_Abstract
{
	/**
	 * Ativa opcao para recuperar senha e solicita confirmacao do usuario
	 * 
	 * @access public
	 * @return boolean
	 */
	public function recovery ()
	{
		try {
			
			$dbUsuario = App_Model_DbTable_Factory::get( 'Usuario' );
			
			$where = array( 
				'user_email = ?' 	=> $this->_data['email'],
				'user_status = ?' 	=> 1
			);	
			
			$row = $dbUsuario->fetchRow( $where );
			
			if ( !empty($row) ) {
				
				$data = array( 'user_hash' => md5(uniqid(time())) );
				$dbUsuario->update( $data, $where );
				
				//Gera mensagem 
				$path = APPLICATION_PATH . '/modules/admin/views/scripts/auth/';
				
				$baseUrl = Zend_Controller_Front::getInstance()->getBaseUrl();

				$url = 'http://'.$_SERVER['SERVER_NAME'].$baseUrl.'/admin/auth/password/hash/'.$data['user_hash'];
								
				$view = new Zend_View();
				$view->setScriptPath( $path );
				$view->assign( 'row', $row );
				$view->assign( 'url', $url );
				
				//Email
				$mail = new Zend_Mail( 'utf-8' );
				
				$mail->addTo( $row->user_email, $row->user_nome );
				$mail->setSubject( 'Recuperar Senha - ' . $this->_config->geral->title );
				$mail->setBodyHtml( $view->render('mail-recovery.phtml') );
				$mail->setFrom( $this->_config->email->address, $this->_config->email->name );
				
				$mail->send();
				
				return true;
				
			}  
			
			return false;
			
		} catch ( Exception $e ) {
			
			return false;
			
		}
		
	}
	
	/**
	 * Envia nova senha para usuario 
	 * 
	 * @access public
	 * @return boolean
	 */
	public function password ()
	{
		try {
			
			$dbUsuario = App_Model_DbTable_Factory::get( 'Usuario' );
			
			$where = array( 
				'user_hash = ?' 	=> $this->_data['hash'],
				'user_status = ?' 	=> 1
			);	
			
			$row = $dbUsuario->fetchRow( $where );
			
			if ( !empty($row) ) {
				
				// Gera nova senha
				$password = App_General_Password::getRand();
				
				$data = array( 
					'user_hash' 	=> md5(uniqid(time())),
					'user_senha' 	=> sha1($password) 
				);
				
				$dbUsuario->update( $data, $where );
				
				//Gera Mensagem
				$path = APPLICATION_PATH . '/modules/admin/views/scripts/auth/';
				
				$view = new Zend_View();
				$view->setScriptPath( $path );
				$view->assign( 'row', $row );
				$view->assign( 'password', $password );
				
				//Email
				$mail = new Zend_Mail( 'utf-8' );
				
				$mail->addTo( $row->user_email, $row->user_nome );
				$mail->setSubject( 'Nova Senha - ' . $this->_config->geral->title );
				$mail->setBodyHtml( $view->render( 'mail-password.phtml' ) );
				$mail->setFrom( $this->_config->email->address, $this->_config->email->name );
				
				$mail->send();
				
				return true;
				
			}
			
			return false;
			
		} catch ( Exception $e ) {
			
			return false;
			
		}
	}
}